package org.deva.erp.base.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.deva.erp.base.entity.BaseEntity;
import org.deva.erp.common.controller.LoginBean;
import org.deva.erp.common.util.OptionModel;
import org.deva.erp.common.util.Permission;
import org.primefaces.context.RequestContext;
import org.primefaces.model.LazyDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Project: erp<br>
 * Description: 基本业务Backing bean代码逻辑封装<br>
 * Copyright (c) 2012<br>
 * All Rights Reserved.<br>
 * @author <a href="mailto:gly420@163.com">GuanLuYong</a><br>
 * @param
 * protected T instance：实体泛型，用于操作(CRUD)当前业务对象<br>
 * protected Map<String, String> queryMap：统一使用查询条件map<br>
 * protected LazyDataModel<T> lazyData：使用primeface的LazyDataModel显示查询结果，可分页<br>
 * protected String model：当前业务操作模式，枚举类型(ADD, MODIFY, REMOVE)<br>
 * protected Permission permission：当前用户对当前菜单的操作权限POJO<br>
 * protected String formId：需要被验证的表单id，传入验证器进行校验<br>
 * private String errorMessage：数据操作错误信息<br>
 */
public abstract class BaseBean<T extends BaseEntity> {
	protected Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	protected LoginBean loginBean;
	
	protected T instance;
	
	protected Map<String, Object> queryMap;
	
	protected LazyDataModel<T> lazyData;
	
	protected String model = null;
	
	protected Permission permission;

	protected String formId = "";
	
	protected String summary;
	
	public BaseBean() { }
	@PostConstruct public void initBean() {
		queryMap = new HashMap<String, Object>(4);
		ensurePermission();
	}
	/**
	 * 获取当前用户对菜单的操作权限
	 */
	public abstract void ensurePermission();
	/**
	 * 查询实体或VO，通过查询条件queryMap
	 */
	public abstract void search();
	/**
	 * 更新实体，调用service.update()方法
	 * @throws Exception 
	 */
	public void editEntity() throws Exception {
		instance.setModBy(loginBean.getUser().getAccount());
		instance.setModDate(new Date());
	}
	/**
	 * 新增实体，调用service.insert()方法
	 * @throws Exception 
	 */
	public void addEntity() throws Exception {
		instance.setAddBy(loginBean.getUser().getAccount());
		instance.setAddDate(new Date());
		instance.setModBy(loginBean.getUser().getAccount());
		instance.setModDate(new Date());
	}
	/**
	 * 删除实体，调用service.remove()方法
	 * @throws Exception
	 */
	public abstract void removeEntity() throws Exception;
	
	public void doAction() {
		OptionModel curModel;
		try {
			curModel = OptionModel.valueOf(model);
		} catch (NullPointerException ne) {		// model is null
			log.error(ne.getMessage());
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_WARN, summary, "没有任何操作"));
			return;
		} catch (IllegalArgumentException ie) {	// no such model
			log.error(ie.getMessage());
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_WARN, summary, "没有此种操作"));
			return;
		}
		if(curModel == null) return;
		try {
			switch(curModel) {
			case ADD:
				addEntity();
				break;
			case MODIFY:
				editEntity();
				break;
			case REMOVE:
				removeEntity();
				break;
			}
		} catch (Exception e) {
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, e.getMessage()));
			log.error(e.getMessage());
			return;
		}
		// 操作成功后，传递参数到页面，可以用此判断，页面也可以不做判断
		RequestContext.getCurrentInstance().addCallbackParam("option_result", "success");
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_INFO, summary, "操作成功,恭喜你."));
	}
	
	public String getOptionName() {
		if(model == null) return "";
		OptionModel curModel = OptionModel.valueOf(model);
		switch(curModel) {
			case ADD: return "#{msgs.btnNew}";
			case MODIFY: return "#{msgs.btnEdit}";
			case QUERY: return "#{msgs.btnQuery}";
			case REMOVE: return "#{msgs.btnRemove}";
		}
		return "";
	}
	// Getter & Setter
	public T getInstance() {
		return instance;
	}

	public void setInstance(T instance) {
		this.instance = instance;
	}

	public Map<String, Object> getQueryMap() {
		return queryMap;
	}

	public void setQueryMap(Map<String, Object> queryMap) {
		this.queryMap = queryMap;
	}
	
	public LazyDataModel<T> getLazyData() {
		return lazyData;
	}

	public void setLazyData(LazyDataModel<T> lazyData) {
		this.lazyData = lazyData;
	}
	
	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}
	
	public String getFormId() {
		return formId;
	}

	public void setFormId(String formId) {
		this.formId = formId;
	}

	public Permission getPermission() {
		return permission;
	}

	public void setPermission(Permission permission) {
		this.permission = permission;
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public LoginBean getLoginBean() {
		return loginBean;
	}

	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}
}
